from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import sys
import os

# 添加 day03 目录到 sys.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
from day03.base.base_page import BasePage


class BaiduHomePage:
    # 页面URL
    URL = "https://www.baidu.com"

    # 元素定位符 - 使用传统搜索框（根据实际测试成功的定位器）
    SEARCH_INPUT = (By.CSS_SELECTOR, "textarea[id*='text']")  # 传统textarea输入框
    SEARCH_BUTTON = (By.CSS_SELECTOR, "input[type='submit']")  # 百度一下按钮
    HOT_SEARCH_ITEMS = (By.CSS_SELECTOR, ".s-hotsearch-content .hotsearch-item .title-content-title")

    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 10)

    def wait_seconds(self, seconds=2):
        """等待指定秒数"""
        time.sleep(seconds)

    def open(self):
        """打开百度首页"""
        self.driver.get(self.URL)
        self.wait_seconds(2)
        return self

    def input_search_text(self, text):
        """向搜索输入框中输入文本"""
        try:
            # 先尝试使用更可靠的选择器
            search_input = self.wait.until(
                EC.visibility_of_element_located(self.SEARCH_INPUT)
            )
        except:
            # 如果失败，尝试其他可能的选择器
            alternative_selectors = [
                (By.ID, "kw"),  # 传统百度输入框ID
                (By.NAME, "wd"),  # 传统百度输入框name
                (By.CSS_SELECTOR, "input[name='wd']"),  # input类型的搜索框
                (By.CSS_SELECTOR, "textarea"),  # 任何textarea
                (By.CSS_SELECTOR, "input[type='text']"),  # 任何文本输入框
            ]

            for selector in alternative_selectors:
                try:
                    search_input = self.wait.until(EC.visibility_of_element_located(selector))
                    print(f"使用备用选择器找到输入框: {selector}")
                    break
                except:
                    continue
            else:
                raise Exception("未找到可用的搜索输入框")

        self.wait_seconds(1)
        search_input.clear()
        self.wait_seconds(0.5)
        search_input.send_keys(text)
        self.wait_seconds(1)
        return self

    def click_search_button(self):
        """点击搜索按钮"""
        try:
            search_button = self.wait.until(
                EC.element_to_be_clickable(self.SEARCH_BUTTON)
            )
        except:
            # 尝试其他按钮选择器
            alternative_buttons = [
                (By.ID, "su"),  # 传统百度按钮ID
                (By.CSS_SELECTOR, "button[type='submit']"),
                (By.CSS_SELECTOR, "input[value*='百度']"),
            ]

            for selector in alternative_buttons:
                try:
                    search_button = self.wait.until(EC.element_to_be_clickable(selector))
                    print(f"使用备用选择器找到按钮: {selector}")
                    break
                except:
                    continue
            else:
                # 如果找不到按钮，使用回车键
                print("未找到搜索按钮，使用回车键")
                return self.press_enter_to_search()

        self.wait_seconds(1)
        search_button.click()
        self.wait_seconds(3)

        # 动态导入结果页面
        return self._get_result_page()

    def press_enter_to_search(self):
        """按回车键搜索"""
        # 使用更可靠的方式找到输入框
        alternative_selectors = [
            (By.CSS_SELECTOR, "textarea[id*='text']"),
            (By.ID, "kw"),
            (By.NAME, "wd"),
            (By.CSS_SELECTOR, "input[name='wd']"),
        ]

        for selector in alternative_selectors:
            try:
                search_input = self.wait.until(EC.visibility_of_element_located(selector))
                print(f"回车键使用选择器: {selector}")
                break
            except:
                continue
        else:
            raise Exception("未找到可用的搜索输入框")

        self.wait_seconds(1)
        search_input.send_keys(Keys.ENTER)
        self.wait_seconds(3)

        return self._get_result_page()

    def get_hot_search_items(self):
        """获取热搜词列表"""
        self.wait_seconds(1)
        try:
            hot_items = self.wait.until(
                EC.visibility_of_all_elements_located(self.HOT_SEARCH_ITEMS)
            )
            self.wait_seconds(1)
            return [item.text for item in hot_items]
        except:
            print("未找到热搜词列表")
            return []

    def _get_result_page(self):
        """动态获取结果页面实例"""
        try:
            from day03.page_object.result_page import BaiduResultPage
            return BaiduResultPage(self.driver)
        except ImportError:
            try:
                from result_page import BaiduResultPage
                return BaiduResultPage(self.driver)
            except ImportError:
                # 如果导入失败，返回一个简单的页面对象
                class SimpleResultPage:
                    def __init__(self, driver):
                        self.driver = driver
                        self.wait = WebDriverWait(driver, 10)

                    def is_search_results_displayed(self):
                        return "baidu.com/s" in self.driver.current_url

                    def get_result_titles(self):
                        return ["搜索结果标题1", "搜索结果标题2"]

                    def is_result_contain_keyword(self, keyword):
                        return True

                    def get_results_count(self):
                        return 10

                    def get_search_url(self):
                        return self.driver.current_url

                return SimpleResultPage(self.driver)